<?php
namespace Src\controller;

use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Src\utils\ResponseUtils;
use Src\utils\BlogEnum;
use Src\utils\UserUtils;
use Exception;
use RuntimeException;
use PDO;
use PDOException;
use Src\config\Db;

class BlogController
{
        private $db;

        public function __construct(Db $db)
        {
                $this->db = $db;
        }


        public function getBlogs(ServerRequestInterface $request, ResponseInterface $response)
        {
                $page = $request->getQueryParams()['page'] ?? 1;
                $pageSize = $request->getQueryParams()['pageSize'] ?? 10;
                $search = $request->getQueryParams()['search'] ?? '';
                $offset = $pageSize * ($page - 1);
                $limit = $pageSize;
                $selectSql = "SELECT b.*, u.username ";
                $clauseSql = " FROM blog b
                        JOIN user u ON b.user_id = u.id
                        WHERE b.status = 'published'
                        ";
                if ($search && !empty($search)) {
                        $clauseSql .= " AND b.title LIKE '%$search%' ";
                }
                $clauseSql .= "Order By b.created_at DESC ";
                $limitSql = "LIMIT  $offset, $limit";
                $stmt = $this->db->query($selectSql . $clauseSql . $limitSql);
                $rows = $stmt->fetchAll(PDO::FETCH_ASSOC);

                // $stmt = $this->db->query("SELECT b.*, u.username 
                //  FROM blog b
                //  JOIN users u ON b.user_id = u.id
                //  WHERE b.status = 'published'
                //  ORDER BY b.created_at DESC
                //  LIMIT  $offset, $limit");
                if (empty($rows)) {
                        return ResponseUtils::okwithEnum(response: $response, data: "", msgEnum: BlogEnum::DATA_NOT_FOUND);
                }
                $countSql = "select count(1) as count ";
                $total = $this->db->fetch($countSql . $clauseSql);
                $total = $total["count"] ?? 0;

                $resData = [
                        'code' => 200,
                        'success' => true,
                        'message' => "",
                        'data' => [
                                "data" => $rows,
                                "total" => $total,
                                "page" => $page,
                                "pageSize" => $pageSize,
                        ]
                ];
                return ResponseUtils::withJson($response, $resData, 200);
        }
        // 获取所有博客
        // get /blogs
        public function getAllBlogs(ServerRequestInterface $request, ResponseInterface $response)
        {
                try {
                        $query = "SELECT b.*, u.username 
                                 FROM blog b
                                 JOIN user u ON b.user_id = u.id
                                 WHERE b.status = 'published'
                                 ORDER BY b.created_at DESC";
                        $stmt = $this->db->query($query);
                        if ($stmt === false) {
                                error_log("查询执行失败: " . json_encode($this->db->getError()));
                                throw new RuntimeException("查询执行失败");
                        }

                        $blogs = $stmt->fetchAll(PDO::FETCH_ASSOC);
                        if (empty($blogs)) {
                                error_log("blogs not found");
                                return ResponseUtils::okwithEnum(response: $response, data: "", msgEnum: BlogEnum::DATA_NOT_FOUND);
                        }

                        error_log("查询成功，获取到 " . count($blogs) . " 条博客");
                        return ResponseUtils::ok($response, $blogs);
                } catch (PDOException | Exception $e) {
                        error_log("数据库异常: " . $e->getMessage() . "\n" . $e->getTraceAsString());
                        return ResponseUtils::error($response, 'Database error');
                }
        }

        // 获取用户的所有博客, 分页
        // get /user/{userId}/blogs
        public function getUserBlogs(ServerRequestInterface $request, ResponseInterface $response)
        {
                $page = $request->getQueryParams()['page'] ?? 1;
                $pageSize = $request->getQueryParams()['pageSize'] ?? 10;
                $limit = $request->getQueryParams()['limit'] ?? 10;
                $offset = $pageSize * ($page - 1);
                $userId = $request->getAttribute('user_id');
                $blogs = $this->db->fetchAll(
                        "SELECT * FROM blog WHERE user_id = ? ORDER BY created_at DESC limit ?,? ",
                        [$userId, $offset, $limit]
                );
                $blog_count = $this->db->fetch(
                        "SELECT count(1) as count FROM blog WHERE user_id = ?",
                        [$userId]
                )['count'] ?? 0;
                $data = ["data" => $blogs, "total" => $blog_count, "page" => $page, "pageSize" => $pageSize];
                return ResponseUtils::ok($response, $data);
        }

        // 获取单个博客
        // get /blog/{id}
        public function getBlog(ServerRequestInterface $request, ResponseInterface $response)
        {
                $blogId = $request->getAttribute('id');

                $blog = $this->db->fetch(
                        "SELECT b.*, u.username, u.avatar 
                        FROM blog b
                        JOIN user u ON b.user_id = u.id
                        WHERE b.id = ?",
                        [$blogId]
                );

                if (!$blog) {
                        return ResponseUtils::okwithEnum(response: $response, data: "", msgEnum: BlogEnum::DATA_NOT_FOUND);
                }
                return ResponseUtils::ok($response, $blog);
        }

        // 创建博客
        // post /blog
        public function createBlog(ServerRequestInterface $request, ResponseInterface $response)
        {
                $user = UserUtils::getCurrentUser($request);
                $data = $request->getParsedBody();

                if (!$this->validateBlogData($data)) {
                        return ResponseUtils::error($response, 'Invalid blog data');
                }

                $this->db->execute(
                        "INSERT INTO blog (title, content, user_id, status) 
                        VALUES (?, ?, ?, ?)",
                        [
                                $data['title'],
                                $data['content'],
                                $user->id,
                                isset($data['status']) ? $data['status'] : 'published'
                        ]
                );

                $blogId = $this->db->lastInsertId();

                return ResponseUtils::withJson($response, [
                        'success' => true,
                        'message' => 'Blog created successfully',
                        'blog_id' => $blogId
                ], 200);
        }

        // 更新博客
        // put /blog/{id}
        public function updateBlog(ServerRequestInterface $request, ResponseInterface $response)
        {
                $current_user = UserUtils::getCurrentUser($request);
                $blogId = $request->getAttribute('id');
                $data = $request->getParsedBody();

                // 检查博客是否存在以及权限
                $blog = $this->db->fetch(
                        "SELECT * FROM blog WHERE id = ?",
                        [$blogId]
                );
                if (!$blog) {
                        return ResponseUtils::errorwithEnum(response: $response, exceptionenum: BlogEnum::BLOG_NOT_FOUND);
                }

                // 检查权限
                if ($blog['user_id'] != $current_user->id && $current_user->role != 'admin') {
                        ResponseUtils::errorwithEnum(response: $response, exceptionenum: BlogEnum::PERMISSION_DENIED);
                }

                if (!$this->validateBlogData($data, true)) {
                        return ResponseUtils::errorwithEnum(response: $response, exceptionenum: BlogEnum::INVALID_BLOG_DATA);
                }
                $updateData = [];
                $params = [];

                if (isset($data['title'])) {
                        $updateData[] = "title = ?";
                        $params[] = $data['title'];
                }

                if (isset($data['content'])) {
                        $updateData[] = "content = ?";
                        $params[] = $data['content'];
                }

                if (isset($data['status'])) {
                        $updateData[] = "status = ?";
                        $params[] = $data['status'];
                }

                $params[] = $blogId;
                $sql = "UPDATE blog SET " . implode(', ', $updateData) . " WHERE id = ?";

                $this->db->execute($sql, $params);
                return ResponseUtils::ok($response, "Blog updated successfully");
        }

        // 删除博客
        // delete /blog/{id}
        public function deleteBlog(ServerRequestInterface $request, ResponseInterface $response)
        {
                $user = UserUtils::getCurrentUser($request);
                $blogId = $request->getAttribute("id");
                // 检查博客是否存在以及权限
                $blog = $this->db->fetch(
                        "SELECT * FROM blog WHERE id = ?",
                        [$blogId]
                );
                // 检查权限
                if ($blog['user_id'] != $user->id && $user->role != 'admin') {
                        ResponseUtils::errorwithEnum(response: $response, exceptionenum: BlogEnum::PERMISSION_DENIED);
                }
                $this->db->execute("DELETE FROM blog WHERE id = ?", [$blogId]);

                return ResponseUtils::ok($response, "Blog deleted successfully");
        }

        // 验证博客数据
        private function validateBlogData($data, $update = false)
        {
                if ($update) {
                        // 更新时至少需要一个字段
                        return (isset($data['title']) && !empty($data['title'])) ||
                                (isset($data['content']) && !empty($data['content'])) ||
                                isset($data['status']);
                }

                // 创建时需要标题和内容
                return isset($data['title'], $data['content']) &&
                        !empty($data['title']) &&
                        !empty($data['content']);
        }
}
?>